<?php

namespace app\health\model;

use think\Model;

class HealthCouponList extends Model
{
    protected $name = 'health_coupon_list';
    protected $autoWriteTimestamp = true;

    /**
     * 关联优惠券
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function coupon()
    {
        return $this->belongsTo(HealthCoupon::class, 'coupon_id');
    }

    /**
     * 处理过期优惠券
     * @param [type] $userId
     * @Author 张旭鹏
     * @DateTime 2023-06-16
     */
    public static function disposeOverdueCoupon($userId)
    {
        //查询过期优惠券
        self::where('user_id', $userId)
            ->where('invalid_time', '<', time())
            ->where('status', '=', 0)
            ->update(['status' => 2]);
    }

    public static function getCanUseCoupon($userId, $goodsIdArr = [])
    {
        $couponList = self::with(['coupon'])
            ->where('user_id', $userId)
            ->where('status', 0)
            ->select();
        $data = [];
        foreach ($couponList as $item) {
            $coupon = $item->coupon;
            if ($coupon) {
                $useGoodsIds = explode(',', $coupon->use_goods_ids);
                $useCoupon = [];
                $useGoodsIntersect = count(array_intersect($goodsIdArr, $useGoodsIds));
                if ($coupon->use_goods_type == 1 || ($coupon->use_goods_type == 2 && $useGoodsIntersect > 0)) {
                    $data[] = $useCoupon;
                }
            }
        }
        return $data;
    }
}
